package com.cropflow.controller;

import com.cropflow.entity.Task;
import com.cropflow.entity.Vehicle;
import com.cropflow.entity.Field;
import com.cropflow.service.TaskService;
import com.cropflow.service.VehicleService;
import com.cropflow.service.FieldService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/tasks")
public class TaskController {
    
    @Autowired
    private TaskService taskService;
    
    @Autowired
    private VehicleService vehicleService;
    
    @Autowired
    private FieldService fieldService;
    
    // 任务下发页面
    @GetMapping("/dispatch")
    public String dispatchPage(Model model) {
        List<Vehicle> vehicles = vehicleService.getAllVehicles();
        List<Field> fields = fieldService.getAllFields();
        List<Task> tasks = taskService.getAllTasks();
        
        model.addAttribute("vehicles", vehicles);
        model.addAttribute("fields", fields);
        model.addAttribute("tasks", tasks);
        model.addAttribute("taskTypes", Task.TaskType.values());
        return "tasks/dispatch";
    }
    
    // 作业监控页面
    @GetMapping("/monitor")
    public String monitorPage(Model model) {
        List<Task> activeTasks = taskService.getActiveTasks();
        model.addAttribute("activeTasks", activeTasks);
        return "tasks/monitor";
    }
    
    // 创建任务API
    @PostMapping("/api/create")
    @ResponseBody
    public ResponseEntity<?> createTask(@RequestBody Task task) {
        try {
            Task savedTask = taskService.saveTask(task);
            return ResponseEntity.ok(savedTask);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("创建任务失败: " + e.getMessage());
        }
    }
    
    // 获取任务状态API
    @GetMapping("/api/{id}/status")
    @ResponseBody
    public ResponseEntity<?> getTaskStatus(@PathVariable Long id) {
        Task task = taskService.getTaskById(id);
        if (task != null) {
            return ResponseEntity.ok(Map.of(
                "status", task.getStatus(),
                "progress", taskService.getTaskProgress(id)
            ));
        }
        return ResponseEntity.notFound().build();
    }
}